<template>
  <div class="main">
    <p class="main_text">审核流程设置</p>

    <!-- ############################################## 表单 ############################################## -->
    <div class="cyr-flex">
      <div class="mb20">
        <el-button type="primary" @click="addAuditBtn" v-if="roleList.write">新增审核</el-button>
      </div>
      <el-table @selection-change="handleSelectionChange" :data="tableData"
         :header-cell-style="{ background: '#f0f6fe' }" v-adaptive :show-overflow-tooltip="true" border>
        <el-table-column type="selection" width="50" />
        <el-table-column label="编号" prop="id" width="80" />
        <el-table-column label="审核类型">
          <template #default="props">
            <el-text style="cursor: pointer; user-select: none" @click="checkData(props.row)">{{
              props.row.processType
            }}</el-text>
          </template>
        </el-table-column>
        <el-table-column label="添加时间" prop="createdAt" />
        <!-- <el-table-column label="更新时间" prop="updatedAt" /> -->
        <el-table-column label="备注" prop="remarks" />
        <el-table-column label="操作">
          <template #default="props">
            <el-button size="small" link type="primary" @click="checkData(props.row)">详情</el-button>
            <el-button size="small" link type="danger" @click="del(props.row)" v-if="roleList.write">删除</el-button>
          </template>
        </el-table-column>
        <!-- <el-table-column label="备注" prop="name" /> -->
      </el-table>
      <smartPager v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total"
        @change="handleCurrentChange" />
    </div>
    <!-- ############################################## 蒙层 ############################################## -->
    <!-- ****************************** 新增审核流程 ****************************** -->
    <el-dialog v-model="RucenterDialogVisible" width="50%" align-center @close="dialogClose">
      <template #header>
        <div class="df aic">
          <el-icon style="color: #fff" size="20">
            <Edit />
          </el-icon>&nbsp;
          <p v-if="btnFlag == false" style="color: #fff">新增审核流程</p>
          <p v-else style="color: #fff">修改审核流程</p>
        </div>
      </template>
      <el-form :model="AddData" label-width="90px" label-position="left" class="df fdc jcc aic">
        <el-form-item label="审核名称：" style="width: 80%">
          <el-input v-model="AddData.processName" :disabled="btnFlag" placeholder="审核名称" />
        </el-form-item>
        <el-form-item label="审核类型：" style="width: 80%">
          <el-select v-model="AddData.tenantId" :disabled="btnFlag" placeholder="请选择审核类型" style="width: 100%">
            <el-option label="入库审核" value="入库审核" />
            <el-option label="出库审核" value="出库审核" />
            <el-option label="调拨审核" value="调拨审核" />
            <el-option label="结算单审核" value="结算单审核" />
            <el-option label="财务结算审核" value="财务结算审核" />
          </el-select>
        </el-form-item>
        <!-- 审批人 -->
        <el-form-item v-for="(item, index) in aduitPersonList" :key="index" :label="index + 1 + '-' + item.label + ':'"
          style="width: 80%">
          <div class="df" style="width: 100%">
            <el-input v-model="item.taskName" placeholder="任务名称" class="mr10" style="width: 100%" />
            <el-tree-select v-model="item.node" :data="sectionData" placeholder="部门" check-strictly @blur="getEmployee"
              @change="changeNode" :render-after-expand="false" class="mr10" filterable />
            <el-select v-model="item.employeeId" placeholder="员工" filterable @focus="employeeTips" class="mr10">
              <el-option v-for="val in employeeList" :key="val.id" :label="val.name" :value="val.id" />
            </el-select>
            <el-button link type="danger" @click="removeAutit(index)">移除</el-button>
          </div>
        </el-form-item>
        <div class="addAuditPerson mb20" @click="addAuditPerson">+ 添加审批人</div>
        <!-- 抄送人 -->
        <el-form-item v-for="(item, index) in copyPersonList" :key="index" :label="index + 1 + '-' + item.label + ':'"
          style="width: 80%">
          <div class="df" style="width: 100%">
            <el-tree-select v-model="item.node" :data="sectionData" placeholder="部门" check-strictly
              @change="changeNode1" @blur="getEmployee1" :render-after-expand="false" class="mr10" filterable
              style="width: 100%" />
            <el-select v-model="item.employeeId" placeholder="员工" filterable @focus="employeeTips1" class="mr10">
              <el-option v-for="val in employeeList1" :key="val.id" :label="val.name" :value="val.id" />
            </el-select>
            <el-button link type="danger" @click="removeCopy(index)">移除</el-button>
          </div>
        </el-form-item>
        <div class="addAuditPerson" @click="addCopyPerson">+ 添加抄送人</div>
        <el-form-item label="备注：" style="width: 80%" class="mt20">
          <el-input type="textarea" v-model="AddData.remarks" placeholder="备注" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="RucenterDialogVisible = false">取消</el-button>
          <el-button type="primary" v-if="btnFlag == true" @click="saveAuidtBtn" :loading="loading"> 保存 </el-button>
          <el-button type="primary" v-else @click="AddAuidtBtn" :loading="loading"> 添加 </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- ****************************** 查看审核流程 ****************************** -->
    <el-dialog v-model="EditcenterDialogVisible" width="30%" title="查看审核流程" align-center>
      <div class="df aic jcc">
        <div>
          <!-- 审批人 -->
          <div v-for="(item, index) in carbonArr" :key="index">
            <div class="df aic">
              <!-- <div class="black_box">{{ item.nameFirst }}</div> -->
              <div class="black_box">{{ item.执行人 }}</div>
              <div>
                <p>{{ item.执行人 }}</p>
                <p style="font-size: 12px; color: #999; margin-top: 4px">{{ item.任务名 }}</p>
              </div>
            </div>
            <div class="black_b" style="height: 30px">
              <div style="width: 2px; height: 30px; background-color: #409ffa"></div>
            </div>
          </div>
          <div class="df aic">
            <div class="black_box">抄</div>
            <div>
              <p>抄送人</p>
              <p style="font-size: 12px; color: #999; margin-top: 4px">已抄送 {{ approverLength }} 人</p>
            </div>
          </div>
          <div class="df">
            <div style="width: 50px"></div>
            <div class="df aic mt10">
              <div style="text-align: center; margin-right: 6px" class="df fww fdc aic" v-for="item in approverArr"
                :key="item">
                <div class="black_boxx">{{ item }}</div>
                <p style="font-size: 12px; color: #999; font-weight: 200; margin-top: 4px">{{ item }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="editAuditBtn">修改</el-button>
          <el-button @click="EditcenterDialogVisible = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  RequestemployeeGetEmployeeByDept,
  RequestNodeGetDeptTree,
  RequestCodeDeployByUserSend,
  RequestCompanyProcessGetlistlimit,
  RequestActivitiDeleteProcess,
  RequestCodeDeployGetProcessDefined,
  RequestActivitiGetTaskDetail,
  RequestCodeDeployGetDefinedProcess,
  RequestCodeDeployGetProcessDefineInfo,
} from '@/api/path/index.js';
import { ElMessage } from 'element-plus';
import { ref } from 'vue';
import { formatTime } from '@/filters/index';
import useAuthorize from '@/hooks/authorize';
import { Edit } from '@element-plus/icons-vue';
let roleList = useAuthorize();
const tableData = ref<any>([]);
const loading = ref<any>(false);
const AddData = ref<any>({
  processName: '',
  tenantId: '',
  node: '',
  remarks: '',
});
const RucenterDialogVisible = ref<any>(false);
const EditcenterDialogVisible = ref<any>(false);
/* 分页器 */
const total = ref<any>(1);
const currentPage = ref(1);
const pageSize = ref(10);
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  getData();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  getData();
};
/* 勾选框 */
const multipleSelection = ref<any>([]);
const handleSelectionChange = (val: any) => {
  multipleSelection.value = val;
};
/* ****************************************************************** 获取部门列表 *******************************************************************/
/* 递归 */
let recursionSectionArr = (arr: any) => {
  arr.forEach((item: any) => {
    item.value = item.id;
    item.label = item.name;
    if (item.type == 'COMPANY') {
      item.company = item.name;
      if (item.children != null) {
        recursionSectionArr(item.children);
      } else {
        return item;
      }
    } else {
      item.sectionName = item.name;
      if (item.children != null) {
        recursionSectionArr(item.children);
      } else {
        return item;
      }
    }
  });
};
/* 获取部门树 */
const sectionData = ref<any>([]);
const getData = () => {
  RequestNodeGetDeptTree(JSON.parse(localStorage.getItem('roleInfo')!).company).then((res: any) => {
    recursionSectionArr(res.resultObj);
    sectionData.value = res.resultObj;
  });
  RequestCompanyProcessGetlistlimit({
    page: currentPage.value,
    rows: pageSize.value,
    companyNode: JSON.parse(localStorage.getItem('roleInfo')!).company,
  }).then((res: any) => {
    res.resultObj.data.forEach((item: any) => {
      item.createdAt = formatTime(item.createdAt);
      item.updatedAt = formatTime(item.updatedAt);
    });
    tableData.value = res.resultObj.data;
    total.value = res.resultObj.total;
  });
};
getData();
const employeeList = ref<any>([]);
const node = ref<any>('');
const employeeList1 = ref<any>([]);
const node1 = ref<any>('');
const changeNode = (e: any) => {
  node.value = e;
};
const getEmployee = () => {
  RequestemployeeGetEmployeeByDept(node.value).then((res: any) => {
    employeeList.value = res.resultObj;
  });
};

/* ****************************************************************** 添加审批人 *******************************************************************/
const aduitPersonList = ref<any>([
  {
    node: '',
    label: '审批人',
    employeeId: '',
    taskName: '',
  },
]);
/* 移除 */
const removeAutit = (event: any) => {
  aduitPersonList.value.splice(event, 1);
};
const employeeTips = () => {
  aduitPersonList.value.forEach((item: any) => {
    if (item.node == '') {
      ElMessage.error('请先选择部门');
    }
  });
};
const addAuditPerson = () => {
  aduitPersonList.value.push({
    node: '',
    label: '审批人',
    employeeId: '',
    taskName: '',
  });
};
/* ****************************************************************** 添加抄送人 *******************************************************************/
const copyPersonList = ref<any>([
  {
    node: '',
    label: '抄送人',
    employeeId: '',
  },
]);
/* 移除 */
const removeCopy = (event: any) => {
  copyPersonList.value.splice(event, 1);
};
const changeNode1 = (e: any) => {
  node1.value = e;
};
const getEmployee1 = () => {
  RequestemployeeGetEmployeeByDept(node1.value).then((res: any) => {
    employeeList1.value = res.resultObj;
  });
};
const employeeTips1 = () => {
  copyPersonList.value.forEach((item: any) => {
    if (item.node == '') {
      ElMessage.error('请先选择部门');
    }
  });
};
const addCopyPerson = () => {
  copyPersonList.value.push({
    node: '',
    label: '抄送人',
    employeeId: '',
  });
};
const addAuditBtn = () => {
  btnFlag.value = false;
  RucenterDialogVisible.value = true;
};
/* ****************************************************************** 添加审核流程 *******************************************************************/
const AddAuidtBtn = () => {
  const CSPerson = ref<any>([]);
  copyPersonList.value.forEach((item: any) => {
    CSPerson.value.push(item.employeeId);
  });
  console.log(AddData.value);
  console.log('审批人', aduitPersonList.value);
  console.log('抄送人', CSPerson.value);
  const blob = new Blob([JSON.stringify(aduitPersonList.value)], {
    type: 'application/json;charset=utf-8',
  });
  // JSON.stringify(CSPerson.value)
  const blob1 = new Blob([JSON.stringify(CSPerson.value)], {
    type: 'application/json;charset=utf-8',
  });
  let AddRoleForm = new FormData();
  AddRoleForm.append('SPPerson', blob);
  AddRoleForm.append('CSPerson', blob1);
  AddRoleForm.append('companyNode', JSON.parse(localStorage.getItem('roleInfo')!).company);
  AddRoleForm.append('processName', AddData.value.processName);
  AddRoleForm.append('tenantId', AddData.value.tenantId);
  AddRoleForm.append('remarks', AddData.value.remarks);
  RequestCodeDeployByUserSend(AddRoleForm).then((res: any) => {
    // loading.value = true
    if (res.success == true) {
      RucenterDialogVisible.value = false;
      ElMessage.success(res.msg);
      // loading.value = false
      getData();
    } else {
      ElMessage.error(res.msg);
      // loading.value = false
    }
  });
};
/* ****************************************************************** 删除 *******************************************************************/
const processIdArr = ref<any>([]);
const del = (row: any) => {
  processIdArr.value.push(row.deploymentId);
  console.log(processIdArr.value);
  let delArr = new FormData();
  delArr.append('processIds', processIdArr.value);
  RequestActivitiDeleteProcess(delArr).then((res: any) => {
    if (res.code == -1) {
      ElMessage.error(res.msg);
    } else if (res.code == 0) {
      ElMessage.success(res.msg);
      getData();
    }
  });
};
/* ****************************************************************** 查看 *******************************************************************/
const approverArr = ref<any>([]); //抄送人
const carbonArr = ref<any>([]); //审批人
const approverLength = ref<any>(); //审批人
const newData = ref<any>();
const checkData = (row: any) => {
  newData.value = row;
  RequestCodeDeployGetProcessDefineInfo(row.processId).then((res: any) => {
    carbonArr.value = res.resultObj;
    approverArr.value = res.resultObj.pop().抄送人;
    approverLength.value = approverArr.value.length;
  });

  EditcenterDialogVisible.value = true;
};
const btnFlag = ref<any>(false);
const editAuditBtn = () => {
  EditcenterDialogVisible.value = false;
  RucenterDialogVisible.value = true;
  AddData.value.processName = newData.value.processName;
  AddData.value.tenantId = newData.value.processType;
  btnFlag.value = true;
};
const saveAuidtBtn = () => {
  const CSPerson = ref<any>([]);
  copyPersonList.value.forEach((item: any) => {
    CSPerson.value.push(item.employeeId);
  });
  console.log(AddData.value);
  console.log('审批人', aduitPersonList.value);
  console.log('抄送人', CSPerson.value);
  const blob = new Blob([JSON.stringify(aduitPersonList.value)], {
    type: 'application/json;charset=utf-8',
  });
  // JSON.stringify(CSPerson.value)
  const blob1 = new Blob([JSON.stringify(CSPerson.value)], {
    type: 'application/json;charset=utf-8',
  });
  let AddRoleForm = new FormData();
  AddRoleForm.append('SPPerson', blob);
  AddRoleForm.append('CSPerson', blob1);
  AddRoleForm.append('companyNode', JSON.parse(localStorage.getItem('roleInfo')!).company);
  AddRoleForm.append('processName', AddData.value.processName);
  AddRoleForm.append('tenantId', AddData.value.tenantId);
  AddRoleForm.append('remarks', AddData.value.remarks);
  RequestCodeDeployByUserSend(AddRoleForm).then((res: any) => {
    // loading.value = true
    if (res.success == true) {
      RucenterDialogVisible.value = false;
      ElMessage.success(res.msg);
      // loading.value = false
      getData();
    } else {
      ElMessage.error(res.msg);
      // loading.value = false
    }
  });
};
const dialogClose = () => {
  AddData.value.processName = '';
  AddData.value.tenantId = '';
  aduitPersonList.value = [
    {
      node: '',
      label: '审批人',
      employeeId: '',
      taskName: '',
    },
  ];
  copyPersonList.value = [
    {
      node: '',
      label: '抄送人',
      employeeId: '',
    },
  ];
};
</script>

<style scoped lang="scss">
.black_box {
  width: 40px;
  height: 40px;
  color: #fff;
  font-size: 20px;
  text-align: center;
  line-height: 40px;
  border-radius: 8px;
  background-color: #449efe;
  margin-right: 16px;
  overflow: hidden;
}

.black_boxx {
  width: 30px;
  height: 30px;
  color: #fff;
  font-size: 14px;
  text-align: center;
  line-height: 30px;
  border-radius: 6px;
  background-color: #449efe;
  overflow: hidden;
}

.black_b {
  width: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.main {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  .top {
    width: 100%;
    background-color: #fff;
  }

  .content {
    width: 100%;
    background-color: #fff;
  }
}

/* 弹出框样式 */
::v-deep .el-dialog__header {
  background-color: #116cf8;
  margin-right: 0;
}

::v-deep .el-dialog__title {
  color: #fff;
}

.addAuditPerson {
  width: 80%;
  height: 30px;
  line-height: 30px;
  text-align: center;
  border-radius: 3px;
  color: #116cf8;
  border: 1px dotted #116cf8;
  user-select: none;
  cursor: pointer;
}
</style>
